#include "input_file.h"
#include <QHBoxLayout>
#include <QFileDialog>
#include "../../Program.h"

InputFile::InputFile(QWidget *parent, const QString& name)
    : QWidget(parent), WidgetInput(name)
{
    _allowEmpty = false;
    _qLineEdit = new QLineEdit(this);
    _qLineEdit->setPlaceholderText("请选择文件...");
    _qToolButton = new QToolButton(this);
    _qToolButton->setIcon(QIcon(":/resource/icon/common/open.png"));
    QLayout* layout = new QHBoxLayout(this);
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(_qLineEdit);
    layout->addWidget(_qToolButton);
    this->setLayout(layout);
    connect(_qToolButton, &QToolButton::clicked, this, &InputFile::qToolButton_clicked);
}

void InputFile::setFilter(const QString& filter)
{
    _filter = filter;
}

void InputFile::setAllowEmpty(bool allowEmpty)
{
    _allowEmpty = allowEmpty;
}

void InputFile::setValue(const QString &value)
{
    QString val = value;
    while (val.startsWith('\'')) val.remove(0, 1);
    while (val.endsWith('\'')) val.remove(val.length() - 1, 1);
    _qLineEdit->setText(val);
}

QString InputFile::getValue() const
{
    return "'" + _qLineEdit->text() + "'";
}

bool InputFile::isEmpty() const
{
    return !_allowEmpty && _qLineEdit->text().isEmpty();
}

void InputFile::qToolButton_clicked(bool)
{
    QString fileName = QFileDialog::getOpenFileName(this,
        "请选择文件",
        QFileInfo(Program::WorkingSpace).absolutePath(),
        _filter,
        nullptr,
        QFileDialog::DontUseNativeDialog);
    if (!fileName.isEmpty())
    {
        _qLineEdit->setText(fileName);
    }
}
